import Taro from '@tarojs/taro'
import { baseURL } from './config'
import { getToken, resetToken } from './auth'
import { MessageBoxUtil } from '@/utils/messageBoxUtil'
import { getErrMsg } from './err-handle'

const isDev = process.env.NODE_ENV === 'development'

const request = {
  baseOptions(params, method = 'GET') {
    let { url, data, contentType } = params
    // let token = getApp().globalData.token
    // if (!token) login()
    const option = {
      isShowLoading: false,
      loadingText: '正在加载',
      url: `${baseURL}${url}`,
      data,
      method,
      header: {
        'content-type': contentType || 'application/json'
      }
    }

    if (getToken()) {
      // 本地存储中取出
      option.header['token'] = getToken()
    }

    // 发起请求
    const p = Taro.request(option)
    return p
      .then(response => {
        const { data: res } = response
        isDev && console.log(`http <-- ${url} result:`, response)

        const { code } = res
        // 自定义code不是2000, 说明业务异常
        if (code !== 2000) {
          const customErrMsg = getErrMsg({ code })
          // token失效
          if ([5000, 50001, 50002, 401].includes(code)) {
            MessageBoxUtil.confirm({
              title: '登录过期',
              content: '登录过期, 是否点击确认按钮重新登录?'
            }, () => {
              // 清除状态管理mobx中的token
              // 重置本地存储的token
              resetToken()
              // 重新加载到首页
              console.log('跳转')
              Taro.reLaunch({
                url: '/pages/login/index'
              })
            })
          }
          isDev && console.log('业务异常 --> ', customErrMsg)
          return Promise.reject(customErrMsg || '业务异常')
        } else {
          // console.log(res)
          // 正常
          return res
        }
      })
      .catch(err => {
        return Promise.reject(err)
      })
  },

  get(params) {
    const defaultParams = {
      url: '',
      data: ''
    }
    const newParmas = {...defaultParams, ...params}
    return this.baseOptions(newParmas)
  },

  post(params) {
    const defaultParams = {
      url: '',
      data: '',
      contentType: 'application/json'
    }
    const newParmas = {...defaultParams, ...params}
    return this.baseOptions(newParmas, 'POST')
  }
}

export default request
